package cn.tedu.bboo.controller;

import cn.tedu.bboo.pojo.entity.User;
import cn.tedu.bboo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserMapper mapper;
    @RequestMapping("/login")
    public int login(@RequestBody User user, HttpSession session, HttpServletResponse response){
        System.out.println("user = " + user);
        User u = mapper.selectByUsername(user.getUsername());
        if(u!=null){
            if(user.getPassword().equals(u.getPassword())){
                session.setAttribute("user",u);
              if(user.getRem()!=null){
                  if(user.getRem()){
                      Cookie c1 = new Cookie("username",user.getUsername());
                      Cookie c2 = new Cookie("password",user.getPassword());
                      response.addCookie(c1);
                      response.addCookie(c2);
                  }
              }
                return 1 ;
            }
            return 2;
        }
        return 3;

    }
    @RequestMapping("/currentUser")
    public User current(HttpSession session){
        return (User) session.getAttribute("user");
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }

}
